var app = getApp();
import ajaxhelper from '../../utils/ajaxhelper.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 1, //预设当前项的值
    dataList: [],//列表数据
    hasRefresh: false,
    isGetMore: false,
    hasMore: true,
    pageSize: 10,
    pageNo: 1,
    isShow: false,//是否显示没有列表的提示图
    subjectId: '',//类型id
    name:'',
    totalPrice:'',
    type:'',
    time:''
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    console.log(option)
    this.getListData(); //获取列表数据
  },

  //列表渲染数据
  getListData:function(id){
    var type;
    if(id =='1'){
      type = null
    }else if(id == '2'){
      type = "WAIT_BUYER_PAY_ALL"
    }else if(id== '3'){
      type = "SUCCESS"
    }
    let param ={
      "orderStatus": type,
      "pageSize":this.data.pageSize,
      "pageNo":this.data.pageNo,
    }
    var token = wx.getStorageSync('Token_date') && wx.getStorageSync('Token_date').Token;
    ajaxhelper.post(app.globalData.frontJSHost + "priceResourceOrder/queryPage?token=" + encodeURIComponent(token), param, this, this.setListData)
  }, 

  setListData(res) {
    console.log(res)
    if(res.status = 200){
      
      var Data = res.data;
      var result = Data.result||'';
      var length = result.length;
      console.log(length)
      var pageNo = this.data.pageNo;
      var hasmore = Data.totalCount - pageNo * this.data.pageSize;

      this.setData({
        pageNo: ++pageNo,
        hasRefresh: false,
        isGetMore: false,
        hasMore: hasmore
        // tip: '上拉加载更多数据'
      })
      
      
        for (var i = 0; i < length; i++){
          
          var gmtCreate = result[i].gmtCreate;
          var time = new Date(gmtCreate).format("yyyy-MM-dd hh:mm:ss")
          console.log(time)
          result[i].time = time;         
        }  
        if (Data && result) {  
          this.setData({
            dataList: this.data.dataList.concat(Data.result),
          })           
        }
          
      }else{
        this.setData({
          hasRefresh: false,
          isGetMore: false,
        })
        wx.showToast({
          title: !!res.message.global ? res.message.global : "请求出错",
          icon: "loading"
        })
      }
      this.setData({
        isShow: true
      })
    }
  ,

  // 点击标题切换当前页时改变样式
  swichNav: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    
    if (this.data.currentTab == id) { return false; }
    else {
      this.setData({
        currentTab: id,
        dataList: [],
        pageNo: 1
      })
    }
    this.getListData(id);//获取列表数据
  },

  //点击列表进行支付
  toast:function(e){
    var id = e.currentTarget.id;
    var app = getApp();
    this.data.requestDetailid = id;
    console.log(id)
    wx.navigateTo({
      url: '../payment/payment?id='+id
    })
  },
  
  //马上支付
  goPay: function (event) {
    var id = event.currentTarget.dataset.id;
    var totalPrice = event.currentTarget.dataset.price;
    var name = event.currentTarget.dataset.name;
    var mediaType = event.currentTarget.dataset.mediaType;
    var sourceId = event.currentTarget.dataset.sourceId;
    console.log(id)
    var that = this;
    var params = {
      id: id
    }
    var token = wx.getStorageSync('Token_date') && wx.getStorageSync('Token_date').Token;
    ajaxhelper.post(app.globalData.frontJSHost + 'priceResourcePay/v1/payOrder?token=' + encodeURIComponent(token), params, this, function (res) {
      console.log(res)
      if (res.status && res.bizCode == 200) {
        if (res.data.data && !res.data.data.params.hasOwnProperty('errorCode')) {
          var payData = res.data.data.params;
          let nonceStr = payData.nonceStr;
          let timeStamp = payData.timeStamp;
          let packageValue = payData.package;
          let signPay = payData.signType;
          let paySign = payData.paySign;
          wx.requestPayment({
            timeStamp: timeStamp,
            nonceStr: nonceStr,
            package: packageValue,
            signType: signPay,
            paySign: paySign,
            success: function (res) {
              console.log(res)
              // 支付成功后关闭音乐，由于有试听地址的原因
              // var backgroundAudioManager = app.backgroundAudioManager;
              // if (backgroundAudioManager.src) {
              //   backgroundAudioManager.stop();
              // }
              // 获取全局音频信息
              var urlObj = wx.getStorageSync('gloalObjUrl');
              urlObj = urlObj ? JSON.parse(urlObj) : {};
              if (urlObj.courseId == sourceId) {
                console.log('购买了当前的' + sourceId);
                urlObj.canView = true;
                wx.setStorage({
                  key: 'gloalObjUrl',
                  data: JSON.stringify(urlObj),
                })
              }
              /////
              wx.redirectTo({
                url: '../successPurchase/successPurchase?name=' + name + '&price=' + totalPrice + '&id=' + id + '&mediaType=' + mediaType + '&sourceId=' + sourceId,
              })
            },
            fail: function (res) {
              that.setData({
                isChecked: false,
                text: '支付'
              })
              wx.showModal({
                title: '支付失败',
                content: '',
                showCancel: false,
                confirmText: '确定',
                confirmColor: '#FF4612',
                success: function (res) {

                }
              })
            }
          })
        }else{
           wx.showToast({
             title: !!res.data.data.params.errorCodeDesc ? res.data.data.params.errorCodeDesc : "订单出错",
            icon: "loading"
          })
        }
      } else {
        wx.showToast({
          title: !!res.msg ? res.msg : "请求出错",
          icon: "loading"
        })
      }
    })
  },
  //下拉刷新
  onPullDownRefresh() {
    this.setData({
      isShow: false
    })
    if (this.data.hasRefresh) return false;
    this.setData({
      dataList: [],
      hasRefresh: true,
      pageNo: 1
    })
    this.getListData(this.data.currentTab)
    setTimeout(function () {
      wx.stopPullDownRefresh()
    }, 1400);
  },
  //上拉加载
  onReachBottom() {
    if (this.data.isGetMore) return false;
    if (this.data.hasRefresh) return false;
    if (this.data.hasMore > 0) {
      this.setData({
        isGetMore: true,
        // tip: '正在加载中...'
      })
      this.getListData(this.data.currentTab);
    } else {
      this.setData({
        isGetMore: false,
        // tip: '没有更多数据了...'
      })
      return false
    }
  },
})